package com.university.logistic.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LogConfig {

    // 定义切入点（示例拦截service包下所有方法）
    @Pointcut("@annotation(com.university.logistic.annotation.MyTransaction)")
    public void pointCut() {}

    @Around("pointCut()")
    public Object logMethodExecution(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getMethod().getName();

        // 记录开始时间和参数
        long startTime = System.currentTimeMillis();
        Object[] args = joinPoint.getArgs();
        log.info("  方法执行开始 [{}] 参数: {}", methodName, Arrays.toString(args));

        Object result = joinPoint.proceed();

            // 计算耗时并记录结果
            long executionTime = System.currentTimeMillis()  - startTime;
            String returnLog = (result != null) ? result.toString()  : "void";
            if(returnLog.length()  > 200) returnLog = returnLog.substring(0,200)  + "..."; // 防止日志过长

            log.info("方法执行 [{}]完成, 耗时: {}ms | 返回: {}",
                    methodName, executionTime, returnLog);
        return result;
    }
}
